'use strict';
const uniID = require('uni-id')
const db = uniCloud.database();
const table = 'uni-id-users';
const dbCmd = db.command
const $ = db.command.aggregate
exports.main = async (event) => {

	// 云函数url，把body转为event所需
	let body = event.body
	if (body) {
		let token = event.headers.uniidtoken
		if (event.isBase64Encoded) {
			body = Buffer.from(body)
		}
		const param = JSON.parse(body) // param为客户端上传的数据
		if (param) {
			event = param
			event.uniIdToken = token
		}
	}

	let params = event.params || {}
	let res = {}
	let payload = {}
	let noCheckAction = ['register', 'checkToken', 'encryptPwd', 'login', 'loginByWeixin', 'sendSmsCode',
		'setVerifyCode', 'loginBySms', 'loginByEmail', 'code2SessionWeixin', 'code2SessionAlipay',
		'checkUserName',
		'get'
	]
	if (noCheckAction.indexOf(event.action) === -1) {
		if (!event.uniIdToken) {
			return {
				code: 403,
				msg: '缺少token'
			}
		}
		payload = await uniID.checkToken(event.uniIdToken)
		if (payload.code && payload.code > 0) {
			return payload
		}
		params.uid = payload.uid
	}

	switch (event.action) {
		case "getusers":
			var size = await db.collection(table).aggregate()
				.match({
					username: params.username === '' ? dbCmd.gte(params.username) : dbCmd.eq(params
						.username)
				})
				.count('total')
				.end()
			var row = await db.collection(table).aggregate()
				.match({
					username: params.username === '' ? dbCmd.gte(params.username) : dbCmd.eq(params
						.username)
				})
				.sort({
					_id: -1
				})
				.skip(params.start)
				.limit(params.limit)
				.end()
			// console.log(response)
			return {
				code: 0,
					data: {
						list: row.data,
						total: size.data.length === 0 ? 0 : size.data[0].total
					}
			};
			break;
		case 'checkUserName':
			var username = params.username
			var collection = db.collection(table)
			var row = await collection.where({
				username: username
			}).limit(1).get()
			if (row.data.length < 1) {
				return {
					code: 0,
					data: {
						code: 200,
						message: "用户不存在"
					},
				}
			}
			return {
				code: 0,
					data: {
						code: 400,
						username: row.data[0].username
					},
			}
			break;
		case 'get':
			var id = event.id;
			var collection = db.collection(table)
			var row = await collection.where({
				_id: id
			}).limit(1).get();
			if (row.data.length < 1) {
				return {
					error: 1,
					message: "数据不存在"
				}
			}
			return {
				error: 0,
					data: {
						user: row.data[0]
					},
			};
			break;
		case 'undata':
			var id = event.id;
			var collection = db.collection(table)
			var row = await collection.where({
					_id: id
				})
				.update({
					userType: params.userType,
					nickname: params.nickname,
					gender: params.gender,
				})
			if (row.updated != 1) {
				return {
					error: 1,
					message: "数据不存在"
				}
			}
			return {
				error: 0,
				data: row,
				message: "修改成功"
			};
			break;
		case 'checkToken':
			res = await uniID.checkToken(event.uniIdToken);
			break;
		case 'register':
			res = await uniID.register(event.params);
			break;
		case 'login':
			res = await uniID.login({
				...event.params,
				// 不指定queryField的情况下
				queryField: ['username', 'email', 'mobile']
			});
			break;
		case 'logout':
			res = await uniID.logout(event.uniIdToken);
			break;
		case 'updatePassword':
			res = await uniID.updatePwd(params);
			break;
		case 'updateNickname':
			res = await uniID.updateNickname(params);
			break;
		case 'setAvatar':
			res = await uniID.setAvatar(params);
			break;
		case 'bindMobile':
			res = await uniID.bindMobile(params);
			break;
		case 'bindEmail':
			res = await uniID.bindEmail(params);
			break;
		case 'loginByWeixin':
			res = await uniID.loginByWeixin(params);
			console.log(res)
			break;
		case 'getRoles':
			res = await uniID.getRoleList(params);
			break;
		case 'addRole':
			res = await uniID.addRole(params);
			break;
		default:
			res = {
				code: 403,
				msg: '非法访问'
			}
			break;
	}

	//返回数据给客户端
	return res
};
